package com.dci.controller.project;

import com.alibaba.fastjson.JSONObject;
import com.dci.context.Config;
import com.dci.model.project.PmsItemInput;
import com.dci.model.schedule.PmsCapitalContract;
import com.dci.result.ResultInfo;
import com.dci.result.ResultUtil;
import com.dci.service.project.PmsItemInputService;
import com.dci.service.schedule.PmsCapitalContractService;
import com.dci.util.UUIDBuild;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;


/**
 * All rights Reserved, Designed By 姑苏区政府大数据中心
 *
 * @version V1.0
 * @Title: null.java
 * @Package com.dci.controller.project
 * @Description: 建设单位业务录入
 * @author: njj
 * @date: 2019/2/25
 * @Copyright: 2019 姑苏区政府大数据中心. All rights reserved.
 * 注意：本内容仅限于姑苏区政府大数据中心内部传阅，禁止外泄以及用于其他的商业目
 */
@Controller
@RequestMapping("/itemInput")
public class PmsItemInputController {

    @Resource
    private PmsItemInputService pmsItemInputService;

    @Resource
    private PmsCapitalContractService pmsCapitalContractService;

    @Value("${upload.path}")
    private String path;

    @Value("${upload.urlP}")
    private String urlP;

    /**
     * 提交表单和上传文件
     *
     * @param files
     * @param form
     * @return ResultInfo 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @PostMapping(value = "/save")
    @ResponseBody
    public ResultInfo save(@RequestParam("uploadFile") MultipartFile[] files, @RequestParam("contractFile") MultipartFile[] contractFile, @RequestParam("form") String form) {
        JSONObject jsonObject = JSONObject.parseObject(form);
        PmsItemInput pmsItemInput = JSONObject.toJavaObject(jsonObject, PmsItemInput.class);
        String fileNames = "";
        String contractFiles = "";
        String filePath = "";
        String contractFilePath = "";
        String id = "";
        String address = "";
        String contractAddress = "";
        String newFileNames = "";
        String newContractFiles = "";
        String contractStatus = "0";
        if (pmsItemInput.getId() == null) {
            id = UUIDBuild.getUUID();
            address = id;
            filePath = path + "/" + address + "/";

            contractAddress = id + "00";
            contractFilePath = path + "/" + contractAddress + "/";

        } else {
            address = pmsItemInput.getId();
            filePath = path + "/" + address + "/";

            contractAddress = address + "00";
            contractFilePath = path + "/" + contractAddress + "/";
        }

        if (files.length != 0) {
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();
                if (fileNames == "") {
                    fileNames += fileName;
                } else {
                    fileNames += ',' + fileName;
                }
                File fileDir = new File(filePath);
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                try {
                    file.transferTo(new File(fileDir.getAbsolutePath(), fileName));
                } catch (IOException e) {
                    continue;
                }
            }
        }
        // 数据库存储的相对路径
        String urlPath = urlP + address + "/";

        if (contractFile.length != 0) {
            for (MultipartFile conFile : contractFile) {
                String contractFileName = conFile.getOriginalFilename();
                if (contractFiles == "") {
                    contractFiles += contractFileName;
                } else {
                    contractFiles += ',' + contractFileName;
                }
                File contractFileDir = new File(contractFilePath);
                if (!contractFileDir.exists()) {
                    contractFileDir.mkdirs();
                }
                try {
                    conFile.transferTo(new File(contractFileDir.getAbsolutePath(), contractFileName));
                } catch (IOException e) {
                    continue;
                }
            }
        }
        // 数据库存储的相对路径
        String contractUrlPath = urlP + contractAddress + "/";

        if ("".equals(fileNames) || contractFiles == null) {
            newFileNames = pmsItemInput.getFileNames();
        } else if ("".equals(pmsItemInput.getFileNames()) || pmsItemInput.getFileNames() == null) {
            newFileNames = fileNames;
        } else {
            newFileNames = pmsItemInput.getFileNames() + "," + fileNames;
        }

        if ("".equals(contractFiles) || contractFiles == null) {
            newContractFiles = pmsItemInput.getContractFile();
        } else if ("".equals(pmsItemInput.getFileNames()) || pmsItemInput.getFileNames() == null) {
            newContractFiles = contractFiles;
        } else {
            newContractFiles = pmsItemInput.getContractFile() + "," + contractFiles;
        }
        return pmsItemInputService.uploadAndSave(form, urlPath, newFileNames, contractUrlPath, newContractFiles, contractStatus);

    }

    /**
     * 查询所有
     *
     * @param
     * @return list集合
     */
    @PostMapping(value = "/selectAll")
    @ResponseBody
    public List<PmsItemInput> selectAll() {
        return pmsItemInputService.selectAll();
    }

    /**
     * 修改状态意见
     *
     * @param object
     * @returnResultInfo 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @PostMapping(value = "/updateStatus")
    @ResponseBody
    public ResultInfo updateStatus(@RequestParam("pmsItemInput") String object) {
        JSONObject jsonObject = JSONObject.parseObject(object);
        PmsItemInput pmsItemInput = JSONObject.toJavaObject(jsonObject, PmsItemInput.class);
        return pmsItemInputService.updateStatus(pmsItemInput);
    }

    /**
     * 删除
     *
     * @param list
     * @return ResultInfo 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @PostMapping(value = "/deleteById")
    @ResponseBody
    public ResultInfo deleteById(@RequestBody List<PmsItemInput> list) {
        if (list.size() > 0) {
            for (PmsItemInput pmsItemInput : list) {
                pmsItemInputService.deleteById(pmsItemInput);
            }
        }
        return ResultUtil.createFail(Config.MESSAGE, 906, null);
    }

    /**
     * 查询所有
     *
     * @param contract
     * @return list集合
     */
    @PostMapping(value = "/contract")
    @ResponseBody
    public List<PmsItemInput> selectByProjectId(@RequestParam("contract") String contract) {
        JSONObject jsonObject = JSONObject.parseObject(contract);
        PmsItemInput pmsItemInput = JSONObject.toJavaObject(jsonObject, PmsItemInput.class);
        return pmsItemInputService.selectByProjectId(pmsItemInput);
    }

    /**
     * 通过projectid查询合同信息（包括合同的历史明细）
     *
     * @param projectId
     * @return list集合
     */
    @PostMapping(value = "/contractByProjectId")
    @ResponseBody
    public List<PmsCapitalContract> contractByProjectId(@RequestParam("projectId") String projectId) {
        return pmsCapitalContractService.selectContractById(projectId);
    }

}
